package com.xxx.baseapplication.http

import androidx.lifecycle.LiveData
import com.xxx.baseapplication.vo.ArticleVO
import com.xxx.baseapplication.vo.BannerVO
import com.xxx.baseapplication.vo.PageVO
import com.xxx.baseapplication.vo.ProjectCategoryVO
import com.xxx.mylibrary.BuildConfig
import com.xxx.mylibrary.http.LiveDataCallAdapterFactory
import com.xxx.mylibrary.util.SP
import com.xxx.mylibrary.vo.ApiResponse
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import java.util.concurrent.TimeUnit

interface WanApi {
    companion object {
        fun get(): WanApi {
            val clientBuilder = OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
            if (BuildConfig.DEBUG) {
                val loggingInterceptor = HttpLoggingInterceptor()
                loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                clientBuilder.addInterceptor(loggingInterceptor)
            }
            clientBuilder.cookieJar(object : CookieJar {
                override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                    if (url.toString().startsWith(
                            "https://www.wanandroid.com/user/login?"
                        )
                    ) {
                        SP.saveCookies(cookies)
                    }
                }

                override fun loadForRequest(url: HttpUrl): MutableList<Cookie> {
                    return SP.getCookies()
                }
            })
            return Retrofit.Builder()
                .baseUrl("https://www.wanandroid.com/")
                .client(clientBuilder.build())
                .addCallAdapterFactory(LiveDataCallAdapterFactory())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(WanApi::class.java)
        }
    }

    /**
     * 首页banner
     */
    @GET("banner/json")
    fun bannerList(): LiveData<ApiResponse<List<BannerVO>>>

    /**
     * 文章列表
     */
    @GET("article/list/{page}/json")
    fun articleList(
        @Path("page") page: Int
    ): LiveData<ApiResponse<PageVO<ArticleVO>>>

    /**
     * 知识体系下文章
     */
    @GET("article/list/{page}/json")
    fun articleList(
        @Path("page") page: Int,
        @Query("cid") cid: Int
    ): LiveData<ApiResponse<PageVO<ArticleVO>>>

    /**
     * 项目分类
     */
    @GET("project/tree/json")
    fun projectTree(): LiveData<ApiResponse<List<ProjectCategoryVO>>>

    /**
     * 项目列表
     */
    @GET("project/list/{page}/json")
    fun projectList(
        @Path("page") page: Int,
        @Query("cid") cid: Int
    ): LiveData<ApiResponse<PageVO<ArticleVO>>>

}